package project.Controller;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import project.Pojo.Result;
import project.Service.FileService;

import java.io.*;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    FileService fileService;

    private InputStream getImgInputStream(String imgPath) throws FileNotFoundException {
        return new FileInputStream(imgPath);
    }


    @PostMapping("/image")
    public Result upLoadImage(MultipartFile file, String username) throws IOException {
        if (file.isEmpty()) return Result.error("图片为空");
        //获取头像文件名
        String name = file.getOriginalFilename();
        if (name == null) return Result.error("文件名为空");
        int i = name.indexOf('.');
        //截取出后缀
        String suffix = name.substring(i);
        if (fileService.selectImgByUsername(username) == null) {
            fileService.insertImg(username, suffix);
        } else {
            fileService.updateImgByUsername(username, suffix);
        }
        //将文件复制到对应目录
        file.transferTo(new File("D:\\Desktop\\心语智疗 - MindSoothe AI\\springboot\\image", username + suffix));
        return Result.success();
    }

    @GetMapping("/getImage")
    public void getIImage(HttpServletResponse resp, String username) throws IOException {
//        取出头像后缀
        String suffix = fileService.selectImgByUsername(username);
        String path = "D:\\Desktop\\心语智疗 - MindSoothe AI\\springboot\\image" + username + suffix;
        InputStream in = getImgInputStream(path);
//        设置响应类型
        resp.setContentType(MediaType.IMAGE_PNG_VALUE);

        IOUtils.copy(in, resp.getOutputStream());
        in.close();
    }
}
